<?php
/**
 * Created by b17
 * 2/17/12 5:24 PM
 */

namespace Managers\TinyMce;

class FileUploader
{
    protected $uploadDir;

    public function __construct()
    {
        $this->uploadDir = \Managers\Utils::sanitizePath(dirname(APPLICATION_PATH) . DIRECTORY_SEPARATOR . \Zend_Registry::get('config')->upload->dir);
        if (!is_writable($this->uploadDir)) {
            throw new \Exception("{$this->uploadDir} is not writable.");
        }
        $this->init();
    }

    public function init()
    {

    }

    public function handle($files)
    {
        $file = $files['upload'];
        if ($file['size'] > 0 && $this->isValidMime($file['type'])) {
            return $this->save($file);
        }
        return false;
    }

    protected function save($file)
    {
        $name = pathinfo($file['name'], PATHINFO_FILENAME);
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);

        $count = 0;
        do {
            $fileName = \Managers\Utils::sanitizePath(
                sprintf("%s%s%s_%d.%s", $this->uploadDir, DIRECTORY_SEPARATOR, $name, $count, $ext));
            $count++;
        } while (file_exists($fileName));
        move_uploaded_file($file['tmp_name'], $fileName);
        $this->transform($fileName);
        return \Managers\Utils::getRelUrl($fileName);
    }

    protected function transform($file)
    {

    }

    protected function isValidMime($mimeType)
    {
        return true;
    }
}
